package cn.bugstack.ai_autoclassification_qwen.controller;

import cn.bugstack.ai_autoclassification_qwen.dto.ClassifyRequest;
import cn.bugstack.ai_autoclassification_qwen.dto.ClassifyResponse;
import cn.bugstack.ai_autoclassification_qwen.service.impl.MultiThreadBatchClassificationServiceimpl;
import cn.bugstack.ai_autoclassification_qwen.service.impl.BatchProductClassificationServiceimpl;
import cn.bugstack.ai_autoclassification_qwen.service.impl.ProductClassificationServiceimpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/products")
@RequiredArgsConstructor
@Slf4j
public class ProductController {

    private final ProductClassificationServiceimpl classificationService;

    private final BatchProductClassificationServiceimpl batchClassificationService;

    private final MultiThreadBatchClassificationServiceimpl batchService;

    // 单次处理一个请求，适用于新增一个商品时自动调用该接口进行AI分类
    @PostMapping("/classify")
    public ResponseEntity<ClassifyResponse> classify(@RequestBody ClassifyRequest request) {
        log.info("classify request start");
        log.info("classify request: {}", request);
        log.info("classify request productId: {}", request.getProductId());
        ClassifyResponse response = classificationService.classifyProduct(request.getProductId());
        return ResponseEntity.ok(response);
    }

    // 批处理，对数据库中的商品数据进行分类
    @GetMapping("/batchClassify")
    public String classifyBatch() {
        log.info("batchclassify request start");
        batchClassificationService.classifyAllProducts();
        return "batchclassify";
    }

    @GetMapping("/multiClassify")
    public String startMulti() {
        // 在单独的后台线程中执行批处理
        Thread t = new Thread(
                () -> batchService.startMultiThreadClassification(),
                "AI_AutoClassification_Qwen"
        );
        t.setDaemon(true);
        t.start();

        // 立刻返回
        return "多线程分类任务已在后台启动";
    }

}

